﻿using FluentValidation;
using PMS.Core.Configuration.CommonEnumConfigs;
using PMS.Core.Utils;
using PMS.Data.Entities.Settings;
using PMS.Web.Framework.Validators;
using PMS.Web.Models.Customers;
using System;
using System.Text.RegularExpressions;

namespace PMS.Web.Validators.Customer
{
    public partial class CustomerLoginValidator : BaseModelValidator<LoginModel>
    {
        public CustomerLoginValidator(CustomerSettings customerSettings, SecuritySettings securitySettings)
        {
            if(customerSettings.UserRegistrationType == UserRegistrationType.MobileOnly)
            {
                RuleFor(x => x.Account).IsMobileNumber(customerSettings).WithMessage(ValidatorRuleString.Validators_MobilePhone);
            }
            else
            {
                RuleFor(x => x.Account).IsMobileNumber(customerSettings).When(x =>
                {
                    //用户登录名要求以字母开头
                    //只要登录信息以1开头的11位数字组合, 以手机方式校验登录信息
                    bool maybeMobile = Regex.IsMatch(x.Account, @"^(1)\d{10}$");
                    return maybeMobile;
                }).WithMessage(ValidatorRuleString.Validators_MobilePhone);
                RuleFor(x => x.Account).EmailAddress().When(x =>
                {
                    //只要登录信息中有@符号, 以邮箱方式校验登录信息
                    bool maybeEmail = x.Account.IndexOf('@', StringComparison.CurrentCultureIgnoreCase) > 0;
                    return maybeEmail;
                }).WithMessage(ValidatorRuleString.Validators_Email);
                RuleFor(x => x.Account).IsUsername(customerSettings).When(x =>
                {
                    //当登录账号即不符合邮箱格式校验也不符合手机号校验，则认为是通过账号登录
                    bool maybeLoginname = !CommonHelper.IsValidEmail(x.Account) && !CommonHelper.IsValidMobile(x.Account);
                    return maybeLoginname;
                });
            }
            //Password rule
            RuleFor(x => x.Password).NotEmpty().WithMessage(ValidatorRuleString.Validation_PasswordNotEmpty);
            //用户登录只校验密码是否输入，不校验密码规则，后台去校验密码是否匹配账号
            //RuleFor(x => x.Password).IsPassword(customerSettings);
        }
    }
}
